package influence.propagation.implementation;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;

import influence.propagation.core.Parser;
import influence.propagation.exception.InputFormatException;

public class DefaultActivityNodeParser implements Parser {

	private File file;
	private Scanner reader = null;
	private StringTokenizer tokens = null;
	private boolean isOpened;

	protected DefaultActivityNodeParser(File file) {
		this.file = file;
	}

	@Override
	public void open() throws FileNotFoundException {
		reader = new Scanner(file);
		if (reader.hasNextLine()) {
			tokens = new StringTokenizer(reader.nextLine(), ",");
		}
		isOpened = true;
	}

	@Override
	public boolean hasMoreToken() {
		if (!isOpened) {
			return false;
		}
		if (!tokens.hasMoreTokens() && !reader.hasNextLine()) {
			return false;
		}
		return true;
	}

	@Override
	public String getNextToken() throws InputFormatException {
		if (tokens.hasMoreTokens()) {
			String token = tokens.nextToken();
			control(token);
			return token;
		}
		if (reader.hasNextLine()) {
			tokens = new StringTokenizer(reader.nextLine(), ",");
			if (tokens.hasMoreTokens()) {
				String token = tokens.nextToken();
				control(token);
				return token;
			}
		}
		throw new IllegalStateException();
	}

	private void control(String token) throws InputFormatException {
		if (!token.matches(DefaultGraphParser.REGEX_1)) {
			throw new InputFormatException("input non valido:" + token);
		}
	}

	@Override
	public void close() {
		reader.close();
	}

}
